<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>神秘竞拍 DApp</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#7B61FF',
                        accent: '#FF4D4F',
                        dark: '#1D2129',
                        light: '#F2F3F5',
                        'neutral-100': '#FFFFFF',
                        'neutral-200': '#F5F5F5',
                        'neutral-300': '#E5E5E5',
                        'neutral-400': '#D9D9D9',
                        'neutral-500': '#BFBFBF',
                        'neutral-600': '#8C8C8C',
                        'neutral-700': '#595959',
                        'neutral-800': '#434343',
                        'neutral-900': '#262626',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                    boxShadow: {
                        'glow': '0 0 15px rgba(22, 93, 255, 0.5)',
                        'glow-lg': '0 0 25px rgba(22, 93, 255, 0.7)',
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-mesh {
                background-image: radial-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px);
                background-size: 30px 30px;
            }
            .text-shadow {
                text-shadow: 0 0 10px rgba(22, 93, 255, 0.7);
            }
            .btn-glow {
                box-shadow: 0 0 10px rgba(22, 93, 255, 0.5);
                transition: all 0.3s ease;
            }
            .btn-glow:hover {
                box-shadow: 0 0 20px rgba(22, 93, 255, 0.7);
                transform: translateY(-2px);
            }
            .animate-pulse-slow {
                animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            .glass {
                background: rgba(17, 25, 40, 0.5);
                backdrop-filter: blur(10px);
                -webkit-backdrop-filter: blur(10px);
                border: 1px solid rgba(255, 255, 255, 0.18);
            }
        }
    </style>
</head>
<body class="font-inter bg-dark text-light min-h-screen overflow-x-hidden bg-mesh">
    <!-- 背景 -->
    <div class="fixed inset-0 z-0">
        <img src="https://picsum.photos/id/1019/1920/1080" alt="竞拍背景" class="w-full h-full object-cover opacity-30">
    </div>
    
    <!-- 顶部导航 -->
    <header class="fixed top-0 left-0 right-0 z-50 glass py-4 px-6 md:px-12 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa-solid fa-gavel text-primary text-2xl"></i>
            <h1 class="text-xl md:text-2xl font-bold tracking-tight">神秘竞拍</h1>
        </div>
        <div class="flex items-center space-x-6">
            <div class="hidden md:flex items-center space-x-4">
                <span class="text-sm text-neutral-400">当前账户:</span>
                <span id="currentAccount" class="text-sm font-medium truncate max-w-[150px]">未连接</span>
            </div>
            <div class="flex items-center space-x-4">
                <span class="text-sm text-neutral-400">账户余额:</span>
                <span id="accountBalance" class="text-sm font-medium">0 ETH</span>
            </div>
            <button id="connectWallet" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-md text-sm font-medium transition-all duration-300 transform hover:scale-105">
                <i class="fa-solid fa-wallet mr-2"></i>连接钱包
            </button>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="relative z-10 container mx-auto px-4 pt-32 pb-20 max-w-6xl">
        <!-- 竞拍物品展示 -->
        <section class="mb-12">
            <div class="glass rounded-2xl p-6 md:p-8 overflow-hidden relative">
                <div class="absolute -right-10 -top-10 w-40 h-40 bg-primary/20 rounded-full filter blur-3xl"></div>
                <div class="absolute -left-10 -bottom-10 w-40 h-40 bg-secondary/20 rounded-full filter blur-3xl"></div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8 relative z-10">
                    <div class="flex flex-col">
                        <div class="relative rounded-xl overflow-hidden mb-4 group">
                            <img src="https://picsum.photos/id/1039/800/600" alt="神秘物品" class="w-full h-auto object-cover transition-transform duration-700 group-hover:scale-105">
                            <div class="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent"></div>
                            <div class="absolute bottom-4 left-4 right-4">
                                <span id="auctionStatus" class="inline-block bg-accent/90 text-white px-3 py-1 rounded-full text-xs font-medium mb-2">拍卖进行中</span>
                                <h2 class="text-2xl md:text-3xl font-bold text-white">古代神秘法典</h2>
                                <p class="text-neutral-300 text-sm mt-1">传说中蕴含无限力量的神秘法典，拥有改变命运的能力</p>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div class="glass rounded-lg p-4">
                                <h3 class="text-neutral-400 text-sm mb-1">当前最高价</h3>
                                <div class="flex items-end">
                                    <span id="currentBid" class="text-2xl font-bold text-white">0 ETH</span>
                                    <span class="text-neutral-400 text-sm ml-1 mb-0.5">≈ ¥0</span>
                                </div>
                            </div>
                            <div class="glass rounded-lg p-4">
                                <h3 class="text-neutral-400 text-sm mb-1">剩余时间</h3>
                                <div class="flex items-end">
                                    <span id="timeRemaining" class="text-2xl font-bold text-white">00:00:00</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex flex-col justify-between">
                        <div>
                            <h3 class="text-xl font-semibold mb-4">拍品详情</h3>
                            <p class="text-neutral-300 mb-6">
                                这件神秘法典据说来自古代文明，蕴含着无尽的智慧和力量。历代拥有者都曾改变了世界的格局。
                                法典由特殊材质制成，历经千年依然保存完好，表面刻有神秘符文，至今无人能完全解读。
                            </p>
                            
                            <div class="glass rounded-lg p-5 mb-6">
                                <h4 class="text-lg font-medium mb-3">竞拍记录</h4>
                                <div id="bidHistory" class="space-y-3 max-h-60 overflow-y-auto pr-2">
                                    <div class="animate-pulse-slow">
                                        <div class="flex justify-between items-center text-sm">
                                            <div>
                                                <span class="text-neutral-300">暂无竞拍记录</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <button id="placeBid" class="bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-lg font-medium btn-glow">
                                <i class="fa-solid fa-gavel mr-2"></i>参与竞拍
                            </button>
                            <button id="withdraw" class="bg-secondary hover:bg-secondary/90 text-white px-6 py-3 rounded-lg font-medium btn-glow">
                                <i class="fa-solid fa-arrow-down-right-from-square mr-2"></i>提取资金
                            </button>
                            <button id="endAuction" class="bg-accent hover:bg-accent/90 text-white px-6 py-3 rounded-lg font-medium btn-glow">
                                <i class="fa-solid fa-stop-circle mr-2"></i>结束拍卖
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 竞拍统计 -->
        <section class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
            <div class="glass rounded-xl p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold">总竞拍次数</h3>
                    <i class="fa-solid fa-gavel text-primary text-xl"></i>
                </div>
                <p id="totalBids" class="text-3xl font-bold text-white">0</p>
                <p class="text-neutral-400 text-sm mt-1">自拍卖开始以来的总竞拍次数</p>
            </div>
            
            <div class="glass rounded-xl p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold">参与人数</h3>
                    <i class="fa-solid fa-users text-secondary text-xl"></i>
                </div>
                <p id="participants" class="text-3xl font-bold text-white">0</p>
                <p class="text-neutral-400 text-sm mt-1">不同账户参与竞拍的数量</p>
            </div>
            
            <div class="glass rounded-xl p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold">当前出价</h3>
                    <i class="fa-solid fa-coins text-accent text-xl"></i>
                </div>
                <p id="currentBidAmount" class="text-3xl font-bold text-white">0 ETH</p>
                <p class="text-neutral-400 text-sm mt-1">当前最高竞拍价格</p>
            </div>
        </section>
        
        <!-- 最近竞拍者 -->
        <section class="mb-12">
            <div class="glass rounded-xl p-6">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-xl font-semibold">最近竞拍者</h3>
                    <a href="#" class="text-primary hover:text-primary/80 text-sm flex items-center">
                        查看全部 <i class="fa-solid fa-arrow-right ml-1"></i>
                    </a>
                </div>
                
                <div id="recentBidders" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    <div class="animate-pulse-slow">
                        <div class="glass rounded-lg p-4 flex items-center">
                            <div class="w-12 h-12 rounded-full bg-neutral-800 flex items-center justify-center text-neutral-500">
                                <i class="fa-solid fa-user"></i>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium">暂无竞拍者</p>
                                <p class="text-xs text-neutral-400">等待第一位竞拍者</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 竞拍弹窗 -->
    <div id="bidModal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
        <div class="relative glass rounded-2xl p-8 max-w-md w-full mx-4 transform transition-all">
            <div class="absolute top-4 right-4">
                <button id="closeBidModal" class="text-neutral-400 hover:text-white">
                    <i class="fa-solid fa-times text-xl"></i>
                </button>
            </div>
            
            <h3 class="text-2xl font-bold mb-6">参与竞拍</h3>
            
            <div class="mb-6">
                <label class="block text-neutral-300 text-sm font-medium mb-2">当前最高价</label>
                <div class="glass rounded-lg p-4">
                    <p id="modalCurrentBid" class="text-xl font-bold">0 ETH</p>
                </div>
            </div>
            
            <div class="mb-6">
                <label for="bidAmount" class="block text-neutral-300 text-sm font-medium mb-2">竞拍金额 (ETH)</label>
                <div class="relative">
                    <input type="number" id="bidAmount" min="0.01" step="0.01" class="w-full bg-neutral-800 border border-neutral-700 rounded-lg px-4 py-3 text-white focus:outline-none focus:ring-2 focus:ring-primary">
                    <span class="absolute right-4 top-3 text-neutral-400">ETH</span>
                </div>
                <p id="bidError" class="text-accent text-sm mt-2 hidden">竞拍金额必须大于当前最高价</p>
            </div>
            
            <button id="confirmBid" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 rounded-lg transition-all">
                确认竞拍
            </button>
        </div>
    </div>

    <!-- 提款弹窗 -->
    <div id="withdrawModal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
        <div class="relative glass rounded-2xl p-8 max-w-md w-full mx-4 transform transition-all">
            <div class="absolute top-4 right-4">
                <button id="closeWithdrawModal" class="text-neutral-400 hover:text-white">
                    <i class="fa-solid fa-times text-xl"></i>
                </button>
            </div>
            
            <h3 class="text-2xl font-bold mb-6">提取资金</h3>
            
            <div class="mb-6">
                <label class="block text-neutral-300 text-sm font-medium mb-2">可提取金额</label>
                <div class="glass rounded-lg p-4">
                    <p id="withdrawableAmount" class="text-xl font-bold">0 ETH</p>
                </div>
            </div>
            
            <button id="confirmWithdraw" class="w-full bg-secondary hover:bg-secondary/90 text-white font-medium py-3 rounded-lg transition-all">
                确认提取
            </button>
        </div>
    </div>

    <!-- 结束拍卖弹窗 -->
    <div id="endAuctionModal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
        <div class="relative glass rounded-2xl p-8 max-w-md w-full mx-4 transform transition-all">
            <div class="absolute top-4 right-4">
                <button id="closeEndAuctionModal" class="text-neutral-400 hover:text-white">
                    <i class="fa-solid fa-times text-xl"></i>
                </button>
            </div>
            
            <h3 class="text-2xl font-bold mb-6">结束拍卖</h3>
            
            <div class="mb-6">
                <p class="text-neutral-300 mb-4">确定要结束当前拍卖吗？结束后将无法继续竞拍，最高出价者将赢得拍品。</p>
                
                <div class="glass rounded-lg p-4 mb-4">
                    <h4 class="text-neutral-300 text-sm mb-2">当前最高出价</h4>
                    <p id="finalBidAmount" class="text-xl font-bold">0 ETH</p>
                    
                    <h4 class="text-neutral-300 text-sm mb-2 mt-4">最高出价者</h4>
                    <p id="highestBidder" class="text-xl font-bold truncate">未确定</p>
                </div>
            </div>
            
            <button id="confirmEndAuction" class="w-full bg-accent hover:bg-accent/90 text-white font-medium py-3 rounded-lg transition-all">
                确认结束拍卖
            </button>
        </div>
    </div>

    <!-- 成功提示 -->
    <div id="successToast" class="fixed bottom-6 right-6 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-500 z-50 flex items-center">
        <i class="fa-solid fa-check-circle mr-2"></i>
        <span id="successMessage">操作成功</span>
    </div>

    <!-- 错误提示 -->
    <div id="errorToast" class="fixed bottom-6 right-6 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-500 z-50 flex items-center">
        <i class="fa-solid fa-exclamation-circle mr-2"></i>
        <span id="errorMessage">操作失败</span>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script>
        // Web3 初始化和交互
        let web3;
        let currentAccount = null;
        let auctionContract = null;
        let contractAddress = "0xYourContractAddress"; // 部署后的合约地址
        let auctionDuration = 24 * 60 * 60; // 24小时（秒）

        // 合约ABI（实际使用时应从编译结果中获取）
        const auctionABI = [
            {
                "inputs": [
                    {
                        "internalType": "uint256",
                        "name": "_duration",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "nonpayable",
                "type": "constructor"
            },
            {
                "anonymous": false,
                "inputs": [
                    {
                        "indexed": true,
                        "internalType": "address",
                        "name": "bidder",
                        "type": "address"
                    },
                    {
                        "indexed": false,
                        "internalType": "uint256",
                        "name": "amount",
                        "type": "uint256"
                    }
                ],
                "name": "BidPlaced",
                "type": "event"
            },
            {
                "anonymous": false,
                "inputs": [
                    {
                        "indexed": true,
                        "internalType": "address",
                        "name": "winner",
                        "type": "address"
                    },
                    {
                        "indexed": false,
                        "internalType": "uint256",
                        "name": "amount",
                        "type": "uint256"
                    }
                ],
                "name": "AuctionEnded",
                "type": "event"
            },
            {
                "inputs": [],
                "name": "endAuction",
                "outputs": [],
                "stateMutability": "nonpayable",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "endTimestamp",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "getAuctionInfo",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "_startTimestamp",
                        "type": "uint256"
                    },
                    {
                        "internalType": "uint256",
                        "name": "_endTimestamp",
                        "type": "uint256"
                    },
                    {
                        "internalType": "uint256",
                        "name": "_highestBid",
                        "type": "uint256"
                    },
                    {
                        "internalType": "address",
                        "name": "_highestBidder",
                        "type": "address"
                    },
                    {
                        "internalType": "enum Auction.State",
                        "name": "_state",
                        "type": "uint8"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [
                    {
                        "internalType": "address",
                        "name": "bidder",
                        "type": "address"
                    }
                ],
                "name": "getBidAmount",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "highestBid",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "highestBidder",
                "outputs": [
                    {
                        "internalType": "address",
                        "name": "",
                        "type": "address"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "owner",
                "outputs": [
                    {
                        "internalType": "address",
                        "name": "",
                        "type": "address"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "placeBid",
                "outputs": [],
                "stateMutability": "payable",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "startTimestamp",
                "outputs": [
                    {
                        "internalType": "uint256",
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "state",
                "outputs": [
                    {
                        "internalType": "enum Auction.State",
                        "name": "",
                        "type": "uint8"
                    }
                ],
                "stateMutability": "view",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "withdraw",
                "outputs": [],
                "stateMutability": "nonpayable",
                "type": "function"
            }
        ];

        // DOM 元素
        const connectWalletBtn = document.getElementById('connectWallet');
        const currentAccountEl = document.getElementById('currentAccount');
        const accountBalanceEl = document.getElementById('accountBalance');
        const placeBidBtn = document.getElementById('placeBid');
        const withdrawBtn = document.getElementById('withdraw');
        const endAuctionBtn = document.getElementById('endAuction');
        const bidModal = document.getElementById('bidModal');
        const closeBidModal = document.getElementById('closeBidModal');
        const confirmBid = document.getElementById('confirmBid');
        const bidAmount = document.getElementById('bidAmount');
        const bidError = document.getElementById('bidError');
        const modalCurrentBid = document.getElementById('modalCurrentBid');
        const withdrawModal = document.getElementById('withdrawModal');
        const closeWithdrawModal = document.getElementById('closeWithdrawModal');
        const confirmWithdraw = document.getElementById('confirmWithdraw');
        const withdrawableAmount = document.getElementById('withdrawableAmount');
        const endAuctionModal = document.getElementById('endAuctionModal');
        const closeEndAuctionModal = document.getElementById('closeEndAuctionModal');
        const confirmEndAuction = document.getElementById('confirmEndAuction');
        const currentBidEl = document.getElementById('currentBid');
        const currentBidAmountEl = document.getElementById('currentBidAmount');
        const timeRemainingEl = document.getElementById('timeRemaining');
        const totalBidsEl = document.getElementById('totalBids');
        const participantsEl = document.getElementById('participants');
        const bidHistoryEl = document.getElementById('bidHistory');
        const recentBiddersEl = document.getElementById('recentBidders');
        const successToast = document.getElementById('successToast');
        const successMessage = document.getElementById('successMessage');
        const errorToast = document.getElementById('errorToast');
        const errorMessage = document.getElementById('errorMessage');
        const auctionStatusEl = document.getElementById('auctionStatus');
        const highestBidderEl = document.getElementById('highestBidder');

        // 初始化应用
        async function init() {
            // 检查 Web3 提供者
            if (window.ethereum) {
                web3 = new Web3(window.ethereum);
                try {
                    // 获取账户
                    const accounts = await window.ethereum.request({ method: 'eth_accounts' });
                    if (accounts.length > 0) {
                        currentAccount = accounts[0];
                        updateAccountInfo();
                    }
                } catch (error) {
                    console.error('获取账户失败:', error);
                }
            } else {
                console.error('未检测到 Web3 提供者，请安装 MetaMask 或其他钱包扩展');
                showErrorToast('请安装 MetaMask 或其他钱包扩展');
            }

            // 初始化合约实例
            if (web3 && contractAddress) {
                auctionContract = new web3.eth.Contract(auctionABI, contractAddress);
                // 加载拍卖数据
                loadAuctionData();
                // 监听拍卖事件
                setupEventListeners();
            }

            // 开始倒计时
            startCountdown();
            
            // 添加事件监听器
            connectWalletBtn.addEventListener('click', connectWallet);
            placeBidBtn.addEventListener('click', openBidModal);
            closeBidModal.addEventListener('click', closeBidModalFunc);
            confirmBid.addEventListener('click', handleBid);
            withdrawBtn.addEventListener('click', openWithdrawModal);
            closeWithdrawModal.addEventListener('click', closeWithdrawModalFunc);
            confirmWithdraw.addEventListener('click', handleWithdraw);
            endAuctionBtn.addEventListener('click', openEndAuctionModal);
            closeEndAuctionModal.addEventListener('click', closeEndAuctionModalFunc);
            confirmEndAuction.addEventListener('click', handleEndAuction);
            
            // 监听账户变化
            if (window.ethereum) {
                window.ethereum.on('accountsChanged', (accounts) => {
                    if (accounts.length > 0) {
                        currentAccount = accounts[0];
                        updateAccountInfo();
                        showSuccessToast('已连接到新账户');
                    } else {
                        currentAccount = null;
                        updateAccountInfo();
                        showErrorToast('已断开连接');
                    }
                });
                
                // 监听网络变化
                window.ethereum.on('chainChanged', () => {
                    window.location.reload();
                });
            }
        }

        // 连接钱包
        async function connectWallet() {
            if (!window.ethereum) {
                showErrorToast('请安装 MetaMask 或其他钱包扩展');
                return;
            }
            
            try {
                const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                currentAccount = accounts[0];
                updateAccountInfo();
                showSuccessToast('钱包连接成功');
            } catch (error) {
                console.error('连接钱包失败:', error);
                showErrorToast('连接钱包失败');
            }
        }

        // 更新账户信息
        async function updateAccountInfo() {
            if (currentAccount) {
                // 显示脱敏地址
                currentAccountEl.textContent = 
                    currentAccount.slice(0, 6) + '...' + currentAccount.slice(-4);
                
                // 获取并显示余额
                try {
                    const balance = await web3.eth.getBalance(currentAccount);
                    const formattedBalance = web3.utils.fromWei(balance, 'ether');
                    accountBalanceEl.textContent = 
                        formattedBalance.slice(0, 8) + ' ETH';
                } catch (error) {
                    console.error('获取余额失败:', error);
                    accountBalanceEl.textContent = '获取失败';
                }
                
                // 检查是否为拍卖所有者
                checkAuctionOwner();
                
                // 获取并显示可提取金额
                if (auctionContract) {
                    const withdrawable = await auctionContract.methods.getBidAmount(currentAccount).call();
                    const formattedWithdrawable = web3.utils.fromWei(withdrawable, 'ether');
                    withdrawableAmount.textContent = `${parseFloat(formattedWithdrawable).toFixed(4)} ETH`;
                }
            } else {
                currentAccountEl.textContent = '未连接';
                accountBalanceEl.textContent = '0 ETH';
                endAuctionBtn.disabled = true;
                endAuctionBtn.classList.add('opacity-50', 'cursor-not-allowed');
            }
        }

        // 加载拍卖数据
        async function loadAuctionData() {
            if (!auctionContract) return;
            
            try {
                // 获取拍卖信息
                const info = await auctionContract.methods.getAuctionInfo().call();
                const highestBid = web3.utils.fromWei(info._highestBid, 'ether');
                const highestBidder = info._highestBidder;
                const state = info._state;
                const endTimestamp = info._endTimestamp;
                
                // 更新UI
                currentBidEl.textContent = `${parseFloat(highestBid).toFixed(4)} ETH`;
                currentBidAmountEl.textContent = `${parseFloat(highestBid).toFixed(4)} ETH`;
                modalCurrentBid.textContent = `${parseFloat(highestBid).toFixed(4)} ETH`;
                finalBidAmount.textContent = `${parseFloat(highestBid).toFixed(4)} ETH`;
                
                // 设置初始竞拍金额
                bidAmount.value = (parseFloat(highestBid) + 0.01).toFixed(2);
                
                // 显示最高出价者
                if (highestBidder === '0x00000000000000000000000000000000000000') {
                    highestBidderEl.textContent = '暂无';
                } else {
                    highestBidderEl.textContent = highestBidder.slice(0, 6) + '...' + highestBidder.slice(-4);
                }
                
                // 更新拍卖状态
                updateAuctionState(state);
                
                // 更新倒计时
                updateCountdown(endTimestamp);
                
                // 获取并更新竞拍历史
                updateBidHistory();
                
                // 更新最近竞拍者
                updateRecentBidders();
                
                // 检查是否为拍卖所有者
                checkAuctionOwner();
                
                // 获取并显示可提取金额
                if (currentAccount) {
                    const withdrawable = await auctionContract.methods.getBidAmount(currentAccount).call();
                    const formattedWithdrawable = web3.utils.fromWei(withdrawable, 'ether');
                    withdrawableAmount.textContent = `${parseFloat(formattedWithdrawable).toFixed(4)} ETH`;
                }
            } catch (error) {
                console.error('加载拍卖数据失败:', error);
                showErrorToast('加载拍卖数据失败');
            }
        }

        // 更新拍卖状态
        function updateAuctionState(state) {
            if (state === '1') { // Ended
                auctionStatusEl.textContent = '拍卖已结束';
                auctionStatusEl.classList.remove('bg-accent/90');
                auctionStatusEl.classList.add('bg-neutral-700');
                placeBidBtn.disabled = true;
                placeBidBtn.classList.add('opacity-50', 'cursor-not-allowed');
                endAuctionBtn.disabled = true;
                endAuctionBtn.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                auctionStatusEl.textContent = '拍卖进行中';
                auctionStatusEl.classList.remove('bg-neutral-700');
                auctionStatusEl.classList.add('bg-accent/90');
            }
        }

        // 开始倒计时
        function startCountdown() {
            updateCountdown();
            setInterval(updateCountdown, 1000);
        }

        // 更新倒计时
        async function updateCountdown(endTimestamp = null) {
            if (!endTimestamp && auctionContract) {
                try {
                    const info = await auctionContract.methods.getAuctionInfo().call();
                    endTimestamp = info._endTimestamp;
                } catch (error) {
                    console.error('获取结束时间失败:', error);
                    return;
                }
            }
            
            if (!endTimestamp) return;
            
            const now = Math.floor(Date.now() / 1000);
            const diff = endTimestamp - now;
            
            if (diff <= 0) {
                timeRemainingEl.textContent = '拍卖已结束';
                return;
            }
            
            const hours = Math.floor(diff / 3600);
            const minutes = Math.floor((diff % 3600) / 60);
            const seconds = diff % 60;
            
            timeRemainingEl.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            // 拍卖即将结束时显示警告
            if (diff < 60 * 10) { // 少于10分钟
                timeRemainingEl.classList.add('text-accent');
            } else {
                timeRemainingEl.classList.remove('text-accent');
            }
        }

        // 检查是否为拍卖所有者
        async function checkAuctionOwner() {
            if (!auctionContract || !currentAccount) {
                endAuctionBtn.disabled = true;
                endAuctionBtn.classList.add('opacity-50', 'cursor-not-allowed');
                return;
            }
            
            try {
                const owner = await auctionContract.methods.owner().call();
                if (currentAccount.toLowerCase() === owner.toLowerCase()) {
                    endAuctionBtn.disabled = false;
                    endAuctionBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                } else {
                    endAuctionBtn.disabled = true;
                    endAuctionBtn.classList.add('opacity-50', 'cursor-not-allowed');
                }
            } catch (error) {
                console.error('检查拍卖所有者失败:', error);
                endAuctionBtn.disabled = true;
                endAuctionBtn.classList.add('opacity-50', 'cursor-not-allowed');
            }
        }

        // 更新竞拍历史
        async function updateBidHistory() {
            if (!auctionContract) return;
            
            try {
                // 获取所有BidPlaced事件
                const events = await auctionContract.getPastEvents('BidPlaced', {
                    fromBlock: 0,
                    toBlock: 'latest'
                });
                
                // 清空历史记录
                bidHistoryEl.innerHTML = '';
                
                if (events.length === 0) {
                    bidHistoryEl.innerHTML = `
                        <div class="animate-pulse-slow">
                            <div class="flex justify-between items-center text-sm">
                                <div>
                                    <span class="text-neutral-300">暂无竞拍记录</span>
                                </div>
                            </div>
                        </div>
                    `;
                    return;
                }
                
                // 更新总竞拍次数
                totalBidsEl.textContent = events.length;
                
                // 计算不同参与者数量
                const uniqueBidders = [...new Set(events.map(event => event.returnValues.bidder))];
                participantsEl.textContent = uniqueBidders.length;
                
                // 显示最近的5条记录
                const recentBids = events.slice(-5).reverse();
                
                recentBids.forEach(event => {
                    const bidder = event.returnValues.bidder;
                    const amount = web3.utils.fromWei(event.returnValues.amount, 'ether');
                    const timestamp = new Date(event.blockTimestamp * 1000).toLocaleString();
                    
                    const bidItem = document.createElement('div');
                    bidItem.className = 'flex justify-between items-center text-sm';
                    bidItem.innerHTML = `
                        <div>
                            <span class="font-medium">${bidder.slice(0, 6)}...${bidder.slice(-4)}</span>
                            <span class="text-neutral-400 ml-2">${timestamp}</span>
                        </div>
                        <div class="font-bold">+${parseFloat(amount).toFixed(4)} ETH</div>
                    `;
                    
                    bidHistoryEl.appendChild(bidItem);
                });
            } catch (error) {
                console.error('获取竞拍历史失败:', error);
            }
        }

        // 更新最近竞拍者
        async function updateRecentBidders() {
            if (!auctionContract) return;
            
            try {
                // 获取所有BidPlaced事件
                const events = await auctionContract.getPastEvents('BidPlaced', {
                    fromBlock: 0,
                    toBlock: 'latest'
                });
                
                // 清空最近竞拍者
                recentBiddersEl.innerHTML = '';
                
                if (events.length === 0) {
                    recentBiddersEl.innerHTML = `
                        <div class="animate-pulse-slow">
                            <div class="glass rounded-lg p-4 flex items-center">
                                <div class="w-12 h-12 rounded-full bg-neutral-800 flex items-center justify-center text-neutral-500">
                                    <i class="fa-solid fa-user"></i>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm font-medium">暂无竞拍者</p>
                                    <p class="text-xs text-neutral-400">等待第一位竞拍者</p>
                                </div>
                            </div>
                        </div>
                    `;
                    return;
                }
                
                // 按出价者分组并计算总出价
                const bidderMap = new Map();
                events.forEach(event => {
                    const bidder = event.returnValues.bidder;
                    const amount = web3.utils.fromWei(event.returnValues.amount, 'ether');
                    
                    if (bidderMap.has(bidder)) {
                        bidderMap.set(bidder, bidderMap.get(bidder) + parseFloat(amount));
                    } else {
                        bidderMap.set(bidder, parseFloat(amount));
                    }
                });
                
                // 按出价金额排序
                const sortedBidders = Array.from(bidderMap.entries())
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 4); // 取前4名
                
                sortedBidders.forEach(([bidder, totalAmount]) => {
                    const bidderItem = document.createElement('div');
                    bidderItem.className = 'glass rounded-lg p-4 flex items-center';
                    bidderItem.innerHTML = `
                        <div class="w-12 h-12 rounded-full bg-neutral-800 flex items-center justify-center text-neutral-500">
                            <i class="fa-solid fa-user"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium truncate">${bidder.slice(0, 6)}...${bidder.slice(-4)}</p>
                            <p class="text-xs text-neutral-400">${parseFloat(totalAmount).toFixed(4)} ETH</p>
                        </div>
                    `;
                    
                    recentBiddersEl.appendChild(bidderItem);
                });
            } catch (error) {
                console.error('获取最近竞拍者失败:', error);
            }
        }

        // 监听拍卖事件
        function setupEventListeners() {
            if (!auctionContract) return;
            
            // 监听新出价事件
            auctionContract.events.BidPlaced({
                fromBlock: 'latest'
            }, (error, event) => {
                if (error) {
                    console.error('监听出价事件失败:', error);
                    return;
                }
                
                console.log('新出价:', event);
                loadAuctionData();
                showSuccessToast('有新的竞拍！');
            });
            
            // 监听拍卖结束事件
            auctionContract.events.AuctionEnded({
                fromBlock: 'latest'
            }, (error, event) => {
                if (error) {
                    console.error('监听拍卖结束事件失败:', error);
                    return;
                }
                
                console.log('拍卖结束:', event);
                loadAuctionData();
                showSuccessToast('拍卖已结束！');
            });
        }

        // 打开竞拍弹窗
        function openBidModal() {
            if (!currentAccount) {
                showErrorToast('请先连接钱包');
                return;
            }
            
            bidModal.classList.remove('hidden');
            setTimeout(() => {
                bidModal.querySelector('div:nth-child(2)').classList.add('scale-100');
                bidModal.querySelector('div:nth-child(2)').classList.remove('scale-95');
            }, 10);
        }

        // 关闭竞拍弹窗
        function closeBidModalFunc() {
            bidModal.querySelector('div:nth-child(2)').classList.add('scale-95');
            bidModal.querySelector('div:nth-child(2)').classList.remove('scale-100');
            setTimeout(() => {
                bidModal.classList.add('hidden');
                bidError.classList.add('hidden');
            }, 300);
        }

        // 处理竞拍
        async function handleBid() {
            if (!auctionContract || !currentAccount) return;
            
            const amount = parseFloat(bidAmount.value);
            const currentBid = parseFloat(modalCurrentBid.textContent);
            
            if (isNaN(amount) || amount <= currentBid) {
                bidError.classList.remove('hidden');
                return;
            }
            
            bidError.classList.add('hidden');
            
            try {
                // 显示加载状态
                confirmBid.disabled = true;
                confirmBid.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i>处理中...';
                
                // 发送交易
                const weiAmount = web3.utils.toWei(amount.toString(), 'ether');
                const receipt = await auctionContract.methods.placeBid().send({
                    from: currentAccount,
                    value: weiAmount
                });
                
                console.log('竞拍成功:', receipt);
                showSuccessToast('竞拍成功！');
                
                // 关闭弹窗
                closeBidModalFunc();
                
                // 刷新数据
                loadAuctionData();
            } catch (error) {
                console.error('竞拍失败:', error);
                showErrorToast('竞拍失败');
                
                // 检查错误类型并显示更友好的消息
                if (error.message.includes('User denied transaction signature')) {
                    showErrorToast('用户拒绝了交易签名');
                } else if (error.message.includes('Bid must be higher than current bid')) {
                    showErrorToast('竞拍金额必须大于当前最高价');
                } else {
                    showErrorToast('发生未知错误，请重试');
                }
            } finally {
                // 恢复按钮状态
                confirmBid.disabled = false;
                confirmBid.innerHTML = '确认竞拍';
            }
        }

        // 打开提款弹窗
        function openWithdrawModal() {
            if (!currentAccount) {
                showErrorToast('请先连接钱包');
                return;
            }
            
            withdrawModal.classList.remove('hidden');
            setTimeout(() => {
                withdrawModal.querySelector('div:nth-child(2)').classList.add('scale-100');
                withdrawModal.querySelector('div:nth-child(2)').classList.remove('scale-95');
            }, 10);
        }

        // 关闭提款弹窗
        function closeWithdrawModalFunc() {
            withdrawModal.querySelector('div:nth-child(2)').classList.add('scale-95');
            withdrawModal.querySelector('div:nth-child(2)').classList.remove('scale-100');
            setTimeout(() => {
                withdrawModal.classList.add('hidden');
            }, 300);
        }

        // 处理提款
        async function handleWithdraw() {
            if (!auctionContract || !currentAccount) return;
            
            try {
                // 显示加载状态
                confirmWithdraw.disabled = true;
                confirmWithdraw.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i>处理中...';
                
                // 发送交易
                const receipt = await auctionContract.methods.withdraw().send({
                    from: currentAccount
                });
                
                console.log('提款成功:', receipt);
                showSuccessToast('提款成功！');
                
                // 关闭弹窗
                closeWithdrawModalFunc();
                
                // 刷新数据
                loadAuctionData();
            } catch (error) {
                console.error('提款失败:', error);
                showErrorToast('提款失败');
                
                // 检查错误类型并显示更友好的消息
                if (error.message.includes('User denied transaction signature')) {
                    showErrorToast('用户拒绝了交易签名');
                } else if (error.message.includes('No funds to withdraw')) {
                    showErrorToast('没有可提取的资金');
                } else {
                    showErrorToast('发生未知错误，请重试');
                }
            } finally {
                // 恢复按钮状态
                confirmWithdraw.disabled = false;
                confirmWithdraw.innerHTML = '确认提取';
            }
        }

        // 打开结束拍卖弹窗
        function openEndAuctionModal() {
            if (!currentAccount) {
                showErrorToast('请先连接钱包');
                return;
            }
            
            endAuctionModal.classList.remove('hidden');
            setTimeout(() => {
                endAuctionModal.querySelector('div:nth-child(2)').classList.add('scale-100');
                endAuctionModal.querySelector('div:nth-child(2)').classList.remove('scale-95');
            }, 10);
        }

        // 关闭结束拍卖弹窗
        function closeEndAuctionModalFunc() {
            endAuctionModal.querySelector('div:nth-child(2)').classList.add('scale-95');
            endAuctionModal.querySelector('div:nth-child(2)').classList.remove('scale-100');
            setTimeout(() => {
                endAuctionModal.classList.add('hidden');
            }, 300);
        }

        // 处理结束拍卖
        async function handleEndAuction() {
            if (!auctionContract || !currentAccount) return;
            
            try {
                // 显示加载状态
                confirmEndAuction.disabled = true;
                confirmEndAuction.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i>处理中...';
                
                // 发送交易
                const receipt = await auctionContract.methods.endAuction().send({
                    from: currentAccount
                });
                
                console.log('拍卖结束成功:', receipt);
                showSuccessToast('拍卖已成功结束！');
                
                // 关闭弹窗
                closeEndAuctionModalFunc();
                
                // 刷新数据
                loadAuctionData();
            } catch (error) {
                console.error('结束拍卖失败:', error);
                showErrorToast('结束拍卖失败');
                
                // 检查错误类型并显示更友好的消息
                if (error.message.includes('User denied transaction signature')) {
                    showErrorToast('用户拒绝了交易签名');
                } else if (error.message.includes('Not auction owner')) {
                    showErrorToast('你不是拍卖所有者');
                } else if (error.message.includes('Auction hasn\'t ended yet')) {
                    showErrorToast('拍卖时间尚未结束');
                } else {
                    showErrorToast('发生未知错误，请重试');
                }
            } finally {
                // 恢复按钮状态
                confirmEndAuction.disabled = false;
                confirmEndAuction.innerHTML = '确认结束拍卖';
            }
        }

        // 显示成功提示
        function showSuccessToast(message) {
            successMessage.textContent = message;
            successToast.classList.remove('translate-y-20', 'opacity-0');
            successToast.classList.add('translate-y-0', 'opacity-100');
            
            setTimeout(() => {
                successToast.classList.add('translate-y-20', 'opacity-0');
                successToast.classList.remove('translate-y-0', 'opacity-100');
            }, 3000);
        }

        // 显示错误提示
        function showErrorToast(message) {
            errorMessage.textContent = message;
            errorToast.classList.remove('translate-y-20', 'opacity-0');
            errorToast.classList.add('translate-y-0', 'opacity-100');
            
            setTimeout(() => {
                errorToast.classList.add('translate-y-20', 'opacity-0');
                errorToast.classList.remove('translate-y-0', 'opacity-100');
            }, 3000);
        }

        // 页面加载完成后初始化
        window.addEventListener('load', init);
    </script>
</body>
</html>